import { ref, onBeforeUnmount } from 'vue'
import { protocol, hostname, webRtcStreamerPort } from '@/utils/request/config'
import { message } from 'ant-design-vue'

// WebRTC视频流播放
export function useWebRtcPlayer({ streamUrl = 'rtsp://stream.strba.sk:1935/strba/VYHLAD_JAZERO.stream' } = {}) {
  const streamUrlRef = ref(streamUrl)
  let webRtcServe = null

  // 检查是否正在播放
  const isPlaying = () => !!webRtcServe

  // 断开WebRTC连接
  const disconnect = () => {
    if (webRtcServe) {
      webRtcServe.disconnect()
      webRtcServe = null
    }
  }

  // 播放WebRTC视频流
  const playStream = () => {
    // 如果当前已有连接，先断开
    disconnect()

    // 检查URL是否为空
    if (!streamUrlRef.value?.trim()) {
      message.error('请输入有效的视频流地址')
      return false
    }

    try {
      // 创建WebRtcStreamer实例
      webRtcServe = new WebRtcStreamer('video-element', `${protocol}//${hostname}:${webRtcStreamerPort}`)

      // 连接到流
      webRtcServe.connect(streamUrlRef.value, null, 'rtptransport=tcp&timeout=60')
      message.success('开始加载视频流')
      return true
    } catch (error) {
      message.error(error.message || '初始化播放器失败')
      webRtcServe = null
      return false
    }
  }

  // 停止视频流播放
  const stopStream = () => {
    if (!webRtcServe) return false

    disconnect()
    return true
  }

  // 组件卸载前清理资源
  onBeforeUnmount(disconnect)

  return {
    streamUrl: streamUrlRef,
    isPlaying,
    playStream,
    stopStream
  }
}
